package test.service.contacts;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;

public class ContactsInfoGetter {
	private ContentResolver m_ContentResolver;
	private Uri DataBaseUri = ContactsContract.Data.CONTENT_URI;
	private static final String[] CONTACTS_DATA_PROJECTION = new String[]{ContactsContract.Data._ID, // 0
		ContactsContract.Data.DATA1,			// 1
	 	};
	ContactsInfoGetter(ContentResolver cr){
		m_ContentResolver = cr;
	}
	public ArrayList<String> getContactsList(){
		ArrayList<String> rtContactsList = new ArrayList<String>();
		Cursor ListCorsor = m_ContentResolver.query(
				DataBaseUri, 
				CONTACTS_DATA_PROJECTION, 
				"mimetype LIKE 'vnd.android.cursor.item/name'", 
				null, 
				null);
		if(ListCorsor.moveToFirst()){
			for (int i = 0 ; ListCorsor.getCount() > i ; i++){
				rtContactsList.add(ListCorsor.getString(1));
				ListCorsor.moveToNext();
			}
			return rtContactsList;
		}
		else
			return null;
	}
	
	public boolean addContact(String name){
		if(name.length() != 0){
			ContentValues contactValue = new ContentValues();
			
			Uri rawContactUri = m_ContentResolver.insert(RawContacts.CONTENT_URI, contactValue);
			int rawContactId = (int) ContentUris.parseId(rawContactUri);
			contactValue.clear();
			
			contactValue.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
			contactValue.put("raw_contact_id", rawContactId);
			contactValue.put(StructuredName.DISPLAY_NAME, name);
			contactValue.put(Data.DATA2, name);
			m_ContentResolver.insert(Data.CONTENT_URI, contactValue);
			
			return true;
		}
		return false;
	}

}
